package com.test17_Lambda;

import org.junit.Test;

/**
 * 方法引用作用：简化Lambda表达式
 * 方法引用形式：
 * 1、引用静态方法             类名称 :: static方法名称
 * 2、引用某个类的普通方法       实例化对象 :: 普通方法
 * 3、引用特定类的普通方法       特定类 :: 普通方法
 * 4、引用构造方法             类名称 :: new
 */
public class YootkDemo_02 {

    @Test
    public void test1() {
        {
            IFunction<Integer> function = (v) -> String.valueOf(v);
            String str = function.convert(987);
            System.out.println(str.length());
        }
        {
            // 引用静态方法
            IFunction<Integer> function = String::valueOf;
            String str = function.convert(987);
            System.out.println(str.length());
        }
    }

    @Test
    public void test2() {
        {
            String str = "沐言优拓：www.yootk.com";
            IFunction2 function = () -> str.toUpperCase();
            System.out.println(function.upper());
        }
        {
            // 引用某个类的普通方法
            String str = "沐言优拓：www.yootk.com";
            IFunction2 function = str::toUpperCase;
            System.out.println(function.upper());
        }
    }

    @Test
    public void test3() {
        {
            IFunction3<String> function = (p1, p2) -> p1.compareTo(p2);
            System.out.println(function.compare("www.yootk.com", "www.YOOTK.com"));
        }
        {
            // 引用特定类的普通方法
            IFunction3<String> function = String::compareTo;
            System.out.println(function.compare("www.yootk.com", "www.YOOTK.com"));
        }
    }

    @Test
    public void test4() {
        {
            IFunction4<Book> function = (t, a, p) -> new Book(t, a, p);
            Book book = function.create("Java从入门到项目实战", "李兴华", 99.8);
            System.out.println(book);
        }
        {
            // 引用构造方法
            IFunction4<Book> function = Book::new;
            Book book = function.create("Java从入门到项目实战", "李兴华", 99.8);
            System.out.println(book);
        }
    }
}

@FunctionalInterface
interface IFunction<T> {
    public String convert(T value);
}

@FunctionalInterface
interface IFunction2 {
    public String upper();
}

@FunctionalInterface
interface IFunction3<P> {
    public int compare(P p1, P p2);
}

class Book {
    private String title;
    private String author;
    private double price;

    public Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    @Override
    public String toString() {
        return "【图书】书名：" + this.title + "、作者：" + this.author + "、价格：" + this.price;
    }
}

@FunctionalInterface
interface IFunction4<R> {
    public R create(String t, String a, double p);
}
